﻿using System;
using System.Web.Mvc;
using SimplePoll.Web.DataAccess;
using SimplePoll.Web.Models;
using Facebook.Web.Mvc;

namespace SimplePoll.Web.Controllers
{
    public class HomeController : Controller
    {
        readonly PollAnswerRepository pollAnswerRepostitory;
        readonly PollRepository pollRepository;
        readonly PollResultRepository pollResultRepository;

        public HomeController()
        {
            pollRepository = new PollRepository();
            pollAnswerRepostitory = new PollAnswerRepository();
            pollResultRepository = new PollResultRepository();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Poll model)
        {
            if (ModelState.IsValid)
            {
                pollRepository.Save(model);
                return RedirectToAction("Index");
            }

            return View();
        }

        public ActionResult Documentation()
        {
            return View();
        }

        public ActionResult FanTab()
        {
            var poll = pollRepository.Retrieve() ?? new Poll();

            return View(poll);
        }

        [FacebookAuthorization(IsFbml=false)]
        public ActionResult Index()
        {
            if (pollAnswerRepostitory.Retrieve(string.Empty) != null)
                return RedirectToAction("PollResults");

            var fbapi = this.GetApi();
            var uid = fbapi.Users.GetLoggedInUser();
            ViewData["facebookId"] = uid.ToString();

            var poll = pollRepository.Retrieve() ?? new Poll();

            return View(poll);
        }

        [HttpPost]
        public ActionResult PostAnswer(PollAnswer pollAnswer)
        {
            if (ModelState.IsValid)
            {
                pollAnswer.FacebookId = pollAnswer.FacebookId;
                pollAnswerRepostitory.Save(pollAnswer);
                return RedirectToAction("PollResults");
            }
            return RedirectToAction("Index");
        }

        public ActionResult PollResults()
        {
            PollResult result = pollResultRepository.Retrieve();
            return View(result);
        }
    }
}